<template>
  <div class="student-form">
    <div class="header">
      <h2>{{ isEdit ? '编辑学生' : '添加学生' }}</h2>
    </div>

    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      class="form"
    >
      <el-form-item label="学号" prop="studentNumber">
        <el-input v-model="form.studentNumber" :disabled="isEdit" />
      </el-form-item>

      <el-form-item label="姓名" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>

      <el-form-item label="性别" prop="gender">
        <el-select v-model="form.gender" placeholder="请选择性别">
          <el-option label="男" value="MALE" />
          <el-option label="女" value="FEMALE" />
        </el-select>
      </el-form-item>

      <el-form-item label="出生日期" prop="birthDate">
        <el-date-picker
          v-model="form.birthDate"
          type="date"
          placeholder="选择日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>

      <el-form-item label="班级" prop="className">
        <el-input v-model="form.className" />
      </el-form-item>

      <el-form-item label="专业" prop="major">
        <el-input v-model="form.major" />
      </el-form-item>

      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" />
      </el-form-item>

      <el-form-item label="电话" prop="phone">
        <el-input v-model="form.phone" />
      </el-form-item>

      <el-form-item label="地址" prop="address">
        <el-input
          v-model="form.address"
          type="textarea"
          :rows="3"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
        <el-button @click="$router.push('/students')">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const route = useRoute()
const router = useRouter()
const formRef = ref(null)

const isEdit = computed(() => route.params.id !== undefined)

const form = ref({
  studentNumber: '',
  name: '',
  gender: '',
  birthDate: '',
  className: '',
  major: '',
  email: '',
  phone: '',
  address: ''
})

const rules = {
  studentNumber: [
    { required: true, message: '请输入学号', trigger: 'blur' },
    { pattern: /^\d{8}$/, message: '学号必须为8位数字', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  birthDate: [
    { required: true, message: '请选择出生日期', trigger: 'change' }
  ],
  className: [
    { required: true, message: '请输入班级', trigger: 'blur' }
  ],
  major: [
    { required: true, message: '请输入专业', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

const fetchStudent = async (id) => {
  try {
    const response = await axios.get(`http://localhost:8080/api/students/${id}`)
    Object.assign(form.value, response.data)
  } catch (error) {
    ElMessage.error('获取学生信息失败')
    router.push('/students')
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (isEdit.value) {
          await axios.put(`http://localhost:8080/api/students/${route.params.id}`, form.value)
          ElMessage.success('更新成功')
        } else {
          await axios.post('http://localhost:8080/api/students', form.value)
          ElMessage.success('添加成功')
        }
        router.push('/students')
      } catch (error) {
        ElMessage.error(isEdit.value ? '更新失败' : '添加失败')
        console.error('Error saving student:', error)
      }
    }
  })
}

onMounted(() => {
  if (isEdit.value) {
    fetchStudent(route.params.id)
  }
})
</script>

<style scoped>
.student-form {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
}

.form {
  max-width: 600px;
  margin: 0 auto;
}
</style> 